package com.example.arffrecorder.graphics;

import java.util.ArrayList;
import java.util.Locale;

import actclient.RoomState;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Parcelable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.speech.tts.TextToSpeech;









import com.example.arffrecoder.services.ARFFLocationService;
import com.example.arffrecoder.services.ARFFLocationService.LocalBinder;
import com.example.arffrecorder.R;
import com.example.arffrecorder.utils.ARFFFileWriter;

public class RecordingActivity extends Activity implements TextToSpeech.OnInitListener{

	boolean serviceBound = false;
	ARFFLocationService mService;
	Button startButton, stopButton, viewButton;
	Intent serviceIntent;
	private EditText fileNameTextArea;
	private String nameOfFile;
	private boolean serviceStarted = false;
	//text to voice object
    private TextToSpeech tts;
	private Intent intent;
	private Intent viewIntent;
	private String ox, oy, oz, type;
	private ArrayList<UserAction> onlineUsers;
	private ArrayList<String> offlineUsers;
	private String roomState;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_recording);
        tts = new TextToSpeech(this, this);

		startButton = (Button) findViewById(R.id.start_record);
		startButton.setOnClickListener(startSensorReading);
		stopButton = (Button) findViewById(R.id.stop_record);
		stopButton.setOnClickListener(stopSensorReading);
		viewButton = (Button) findViewById(R.id.viewButton);
		viewButton.setOnClickListener(viewRoomListener);
		stopButton.setEnabled(false);
		fileNameTextArea = (EditText) findViewById(R.id.fileName);
		fileNameTextArea.addTextChangedListener(watcher);
		intent = new Intent(this, ARFFLocationService.class);
		viewIntent = new Intent(this, VisualizeActivity.class);
	}
	//stop the text to speech functionality when the activity is destroyed
	 @Override
	    public void onDestroy() {
	        // stop text to voice
	        if (tts != null) {
	            tts.stop();
	            tts.shutdown();
	        }
	        super.onDestroy();
	    }
	/**receive information from the service (raw_data: acceleration values or label of the activity)
	 * 
	 */
	private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
        	String info_received = intent.getStringExtra("message_type");
        	if (info_received.equals("raw_data")){
	        	ox = intent.getStringExtra("ox");
	        	oy = intent.getStringExtra("oy"); 
	        	oz = intent.getStringExtra("oz"); 
	        	roomState = intent.getStringExtra("room_state");
	        	displayInfo(ox,oy,oz); 
        	}
        	if (info_received.equals("display_label")){
        		type = intent.getStringExtra("activity_value");
        		displayActivity(type);
        	}
        
        }
    }; 
    
    /**
     * save data from the edit file in a variable so that it can be passed when the orientation change
     */
	TextWatcher watcher = new TextWatcher() {
		
		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			// TODO Auto-generated method stub
			nameOfFile = fileNameTextArea.getText().toString();
		}
		
		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			nameOfFile = fileNameTextArea.getText().toString();
			
		}
		
		@Override
		public void afterTextChanged(Editable s) {
			// TODO Auto-generated method stub
			nameOfFile = fileNameTextArea.getText().toString();
		}
	};
	/** Listener for startButton 
	 * 
	 */
	View.OnClickListener startSensorReading = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			if (isFileNameValid()){
				
				ImageView recordImage = (ImageView) findViewById(R.id.recordImage);
				recordImage.setImageResource(R.drawable.record_start);
				startButton = (Button)findViewById(R.id.start_record);
				stopButton = (Button) findViewById(R.id.stop_record);
				stopButton.setEnabled(true);
				startButton.setEnabled(false);
				if (serviceBound == false) {
					serviceBound = true;
					EditText fileName = (EditText) findViewById(R.id.fileName);
					fileName.setEnabled(false);
					intent.putExtra("fileName", nameOfFile + ".arff");
					if (!serviceStarted){
						startService(intent);
						serviceStarted = true;
					}
					
					bindService(intent, mConnection, Context.BIND_AUTO_CREATE);		
					registerReceiver(broadcastReceiver, new IntentFilter(ARFFLocationService.BROADCAST_ACTION));
				}
			}
		}
	};
	/** Listener for stopButton
	 * 
	 */
	View.OnClickListener stopSensorReading = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			ImageView recordImage = (ImageView) findViewById(R.id.recordImage);
			recordImage.setImageResource(R.drawable.record_stop);
			
			startButton = (Button)findViewById(R.id.start_record);
			stopButton = (Button) findViewById(R.id.stop_record);
			
			startButton.setEnabled(true);
			stopButton.setEnabled(false);
			if (serviceBound) {
				EditText fileName = (EditText) findViewById(R.id.fileName);
				fileName.setEnabled(true);		
				stopService(intent);
				
				unregisterReceiver(broadcastReceiver);
				unbindService(mConnection);
				serviceBound = false;
			}
		}
	};
	View.OnClickListener viewRoomListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			viewIntent.putExtra("room_state", roomState);
			startActivity (viewIntent);
		}
	};
	

	@Override
	protected void onStart() {
		super.onStart();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.recording, menu);
		return true;
	}
	/**
	 * actions to be taken if one item from the menu is chosen
	 */
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {
		case R.id.home_page:

			Intent i = new Intent(RecordingActivity.this, MainScreen.class);
			startActivity(i);
			return true;
		case R.id.help:
			Toast.makeText(RecordingActivity.this,
					"Press start button to record data from accelerometer",
					Toast.LENGTH_SHORT).show();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	protected void onResume() {
		super.onResume();
		if (serviceBound){
			if (!serviceStarted){
				startService(intent);
				serviceStarted = true;
			}
			bindService(intent, mConnection, Context.BIND_AUTO_CREATE);	
			registerReceiver(broadcastReceiver, new IntentFilter(ARFFLocationService.BROADCAST_ACTION));
		}
	}

	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onStop() {
		
		super.onStop();
		if (isFinishing() && serviceBound){
			unbindService(mConnection);
			serviceBound = false;
			unregisterReceiver(broadcastReceiver);
			//stopService(intent);
		}
	}
	
	/** in case orientation changes do not recreate activity (stop service)
	 * 
	 */
	@Override
    public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE){
			setContentView(R.layout.activity_recording_land);
		}
		else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT)
			setContentView(R.layout.activity_recording);
		EditText fileName = (EditText) findViewById(R.id.fileName);
		EditText oxText = (EditText) findViewById(R.id.ox_data);
		EditText oyText = (EditText) findViewById(R.id.oy_data);
		EditText ozText = (EditText) findViewById(R.id.oz_data);
		TextView activityText = (TextView) findViewById(R.id.textViewActivity);

		fileName.setText(nameOfFile);
		
		oxText.setText(ox); 
		oyText.setText(oy);
		ozText.setText(ox);
		activityText.setText(type);

	
		Button newStartButton = (Button) findViewById(R.id.start_record);
		Button newStopButton = (Button) findViewById(R.id.stop_record);

		newStartButton.setOnClickListener(startSensorReading);
		newStopButton.setOnClickListener(stopSensorReading);

		newStartButton.setEnabled(startButton.isEnabled());
		newStopButton.setEnabled(stopButton.isEnabled());
		
		ImageView recordImg = (ImageView)findViewById(R.id.recordImage);
		
		if(stopButton.isEnabled()){
			recordImg.setImageResource(R.drawable.record_start);
		}
		else{
			recordImg.setImageResource(R.drawable.record_stop);
		}
	} 	
	
	private ServiceConnection mConnection = new ServiceConnection() {
		@Override
		public void onServiceConnected(ComponentName className, IBinder service) {
			// We've bound to LocalService, cast the IBinder and get
			// LocalService instance
			LocalBinder binder = (LocalBinder) service;
			mService = binder.getService();
			//myMessenger = new Messenger (service);
		}
		@Override
		public void onServiceDisconnected(ComponentName arg0) {
			serviceBound = false;
		}
	
	};
	/** displayInfo
	 * 
	 * @param ox
	 * @param oy
	 * @param oz
	 */
	public void displayInfo(String ox, String oy, String oz){
		
		EditText oxData = (EditText) findViewById(R.id.ox_data);
		oxData.setText(ox);

		EditText oyData = (EditText) findViewById(R.id.oy_data);
		oyData.setText(oy);

		EditText ozData = (EditText) findViewById(R.id.oz_data);
		ozData.setText(oz);
	}
	/** display activity label set by the classifier
	 * 
	 * @param activity
	 */
	public void displayActivity(String activity){
		TextView activityDisplay = (TextView) findViewById(R.id.textViewActivity);
		String label = (String) activityDisplay.getText();
		if (!label.equals(activity)){
			activityDisplay.setText(activity);
			talk(activity);
		}
	}
	/**method for checking if the filename is valid for starting recording
	 * 
	 */
	public boolean isFileNameValid(){
		EditText fileName = (EditText) findViewById(R.id.fileName);
		nameOfFile = fileName.getEditableText().toString();
		if (fileName != null)
			if (ARFFFileWriter.getInstance().isFileNameValid(nameOfFile)){
				if (ARFFFileWriter.getInstance().fileExists(nameOfFile + ".arff")){
					Toast.makeText(this, "File with this name already exists!", Toast.LENGTH_SHORT).show();
					return false;
				}
				else 
					return true;
			}
			else {
				Toast.makeText(this, "Invalid filename!", Toast.LENGTH_SHORT).show();
				return false;
			}
		else{
			Toast.makeText(this, "Unexpected input error!", Toast.LENGTH_SHORT).show();
			return false;
		}
	}	
	/**
	 * get file extension from the option chosen by the user from the combobox
	 */
	/*public String getExtension(){
		Spinner extension = (Spinner) findViewById(R.id.spinner1);
		if (extension != null)
			return extension.getSelectedItem().toString();
		else
			return "";
	}*/

	@Override
    public void onInit(int status) {
        if (status == TextToSpeech.SUCCESS) {
            int result = tts.setLanguage(Locale.US); 
            if (result == TextToSpeech.LANG_MISSING_DATA
                    || result == TextToSpeech.LANG_NOT_SUPPORTED) 
                Log.e("TTS", "This Language is not supported");              
        } 
        else {
            Log.e("TTS", "Initilization Failed!");
        }
 
    }
	/**text to voice 
	 * 
	 * @param text
	 */
	private void talk(String text) { 
        tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
    }
}